package ngames.com.sushitv.action;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import ngames.com.sushitv.Fragment.RegisterFragment;
import ngames.com.sushitv.R;
import ngames.com.sushitv.activity.LoginActivity;
import ngames.com.sushitv.activity.MainActivity;
import ngames.com.sushitv.base.BaseAction;
import ngames.com.sushitv.core.ModelCallback;
import ngames.com.sushitv.entity.UserInfo;
import ngames.com.sushitv.interfaces.DialogButtonListener;
import ngames.com.sushitv.tools.AppUtil;
import ngames.com.sushitv.tools.Constants;
import ngames.com.sushitv.view.DialogApp;

/**
 * Created by Jeffrey on 2016/8/2.
 */
public class RegisterAction extends BaseAction implements View.OnClickListener {
    public static final String EXTRA_TYPE = "EXTRA_TYPE";
    public static final String EXTRA_USERINFO = "EXTRA_USERINFO";

    private String mAccountType;                    //fb账号绑定注册；app注册
    private UserInfo mUserInfoFB;                   //fb注册时，存fb的信息
    private String mRegisterType;

    private FBLoginAction mFBLoginAction;
    private SendSmsAction mSendSmsAction;
    private EditText mEmailEdt;
    private EditText mPasswordEdt;
    private EditText mConfirmPasswordEdt;
    private EditText mUsernameEdt;

    private EditText mCodesEdt;

    public RegisterAction(Activity activity, View baseView) {
        super(activity, baseView);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        View view = mBaseView;
        Intent intent = mActivity.getIntent();
        mAccountType = intent.getStringExtra(EXTRA_TYPE);

        mEmailEdt = (EditText) view.findViewById(R.id.email);
        if (Constants.ACCOUNT_TYPE_APP.equals(mAccountType)) {
            setTitle(R.string.sign_up);
            TextView signUpFBTv = (TextView) view.findViewById(R.id.txv_login_fb);
            signUpFBTv.setVisibility(View.VISIBLE);
            signUpFBTv.setOnClickListener(this);
            setRegisterType(view);
            mFBLoginAction = new FBLoginAction(mActivity, view);
            mFBLoginAction.onCreate();
        } else {
            setTitle(R.string.sign_up_with_facebook);
            mUserInfoFB = (UserInfo) intent.getSerializableExtra(EXTRA_USERINFO);
            mEmailEdt.setText(mUserInfoFB.getEmail());
            mEmailEdt.setSelection(mEmailEdt.getText().length());
        }

        view.findViewById(R.id.btn_sign_up).setOnClickListener(this);
        view.findViewById(R.id.tvx_have_account).setOnClickListener(this);
    }

    private void setRegisterType(View baseView) {
        View eForm = baseView.findViewById(R.id.email_register_form);
        View pForm = baseView.findViewById(R.id.phone_register_form);
        if (RegisterFragment.REGISTER_TYPE_PHONE.equals(mRegisterType)) {
            eForm.setVisibility(View.GONE);
            pForm.setVisibility(View.VISIBLE);
            mUsernameEdt = (EditText) baseView.findViewById(R.id.pr_edt_username);
            mPasswordEdt = (EditText) baseView.findViewById(R.id.pr_password);
            mConfirmPasswordEdt = (EditText) baseView.findViewById(R.id.pr_edt_confirm_password);
            mCodesEdt = (EditText) baseView.findViewById(R.id.edt_codes);
            mSendSmsAction = new SendSmsAction(mActivity, baseView);
            mSendSmsAction.setSmsType(Constants.SMS_TYPE_REGISTER);
            mSendSmsAction.onCreate();
        } else {
            eForm.setVisibility(View.VISIBLE);
            if (pForm != null) {
                pForm.setVisibility(View.GONE);
            }
            mUsernameEdt = (EditText) baseView.findViewById(R.id.edt_username);
            mPasswordEdt = (EditText) baseView.findViewById(R.id.password);
            mConfirmPasswordEdt = (EditText) baseView.findViewById(R.id.edt_confirm_password);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mFBLoginAction != null) {
            mFBLoginAction.onDestroy();
        }
        if (mSendSmsAction != null) {
            mSendSmsAction.onDestroy();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mFBLoginAction != null) {
            mFBLoginAction.onActivityResult(requestCode, resultCode, data);
        }
        if (mSendSmsAction != null) {
            mSendSmsAction.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_sign_up:
                if (RegisterFragment.REGISTER_TYPE_PHONE.equals(mRegisterType)) {
                    attemptRegisterPhone();
                } else {
                    attemptRegister();
                }
                break;
            case R.id.txv_login_fb:
                mFBLoginAction.loginFB();
                break;
            case R.id.tvx_have_account:
                mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
                break;
        }
    }

    public void setRegisterType(String registerType) {
        mRegisterType = registerType;
    }

    /**
     * email注册
     */
    private void attemptRegister() {
        mEmailEdt.setError(null);
        mPasswordEdt.setError(null);
        mConfirmPasswordEdt.setError(null);
        mUsernameEdt.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailEdt.getText().toString();
        String password = mPasswordEdt.getText().toString();
        String confirmPassword = mConfirmPasswordEdt.getText().toString();
        String username = mUsernameEdt.getText().toString();

        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(email)) {
            mEmailEdt.setError(getString(R.string.error_field_required));
            focusView = mEmailEdt;
            cancel = true;
        } else if (!AppUtil.isEmailValid(email)) {
            mEmailEdt.setError(getString(R.string.error_invalid_email));
            focusView = mEmailEdt;
            cancel = true;
        } else if (TextUtils.isEmpty(password)) {
            mPasswordEdt.setError(getString(R.string.enter_password));
            focusView = mPasswordEdt;
            cancel = true;
        } else if (!AppUtil.isPasswordValid(password)) {
            mPasswordEdt.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordEdt;
            cancel = true;
        } else if (TextUtils.isEmpty(confirmPassword)) {
            mConfirmPasswordEdt.setError(getString(R.string.error_field_required));
            focusView = mConfirmPasswordEdt;
            cancel = true;
        } else if (!password.equals(confirmPassword)) {
            mConfirmPasswordEdt.setError(getString(R.string.error_invalid_password));
            focusView = mConfirmPasswordEdt;
            cancel = true;
        } else if (TextUtils.isEmpty(username)) {
            mUsernameEdt.setError(getString(R.string.error_field_required));
            focusView = mUsernameEdt;
            cancel = true;
        } else if (!AppUtil.isUsernameValid(username)) {
            mUsernameEdt.setError("username error");
            focusView = mUsernameEdt;
            cancel = true;
        }
        if (cancel) {
            focusView.requestFocus();
        } else {
            showProgress(true);
            register(username, email, password);
        }
    }

    private void register(String name, String email, String password) {
        getAppModel().getUserService().register(mUserInfoFB, name, email, password, new ModelCallback<UserInfo>() {
            @Override
            public void onBeforeRequest(String urlTag) {

            }

            @Override
            public void onSuccess(UserInfo data) {
                showProgress(false);
                if (Constants.ACCOUNT_TYPE_APP.equals(mAccountType) || TextUtils.isEmpty(data.getToken())) {
                    final DialogApp activationDialog = new DialogApp(mActivity);
                    activationDialog.setMessage("登录注册邮箱激活账号！");
                    activationDialog.setRightBtn("OK", new DialogButtonListener() {
                        @Override
                        public void onClick() {
                            activationDialog.dismiss();
                            mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
                        }
                    });
                    activationDialog.show();
                } else {
                    mActivity.startActivity(new Intent(mActivity, MainActivity.class));
                }
                Toast.makeText(getAppApplication(), "success", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                showProgress(false);
                Toast.makeText(getAppApplication(), "Registration failed!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 手机号码注册
     */
    private void attemptRegisterPhone() {
        mUsernameEdt.setError(null);
        mPasswordEdt.setError(null);
        mConfirmPasswordEdt.setError(null);

        String username = mUsernameEdt.getText().toString();
        String password = mPasswordEdt.getText().toString();
        String confirmPassword = mConfirmPasswordEdt.getText().toString();

        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(username)) {
            mUsernameEdt.setError(getString(R.string.error_field_required));
            focusView = mUsernameEdt;
            cancel = true;
        } else if (!AppUtil.isUsernameValid(username)) {
            mUsernameEdt.setError("username error");
            focusView = mUsernameEdt;
            cancel = true;
        } else if (TextUtils.isEmpty(password)) {
            mPasswordEdt.setError(getString(R.string.enter_password));
            focusView = mPasswordEdt;
            cancel = true;
        } else if (!AppUtil.isPasswordValid(password)) {
            mPasswordEdt.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordEdt;
            cancel = true;
        } else if (TextUtils.isEmpty(confirmPassword)) {
            mConfirmPasswordEdt.setError(getString(R.string.error_field_required));
            focusView = mConfirmPasswordEdt;
            cancel = true;
        } else if (!password.equals(confirmPassword)) {
            mConfirmPasswordEdt.setError(getString(R.string.error_invalid_password));
            focusView = mConfirmPasswordEdt;
            cancel = true;
        } else if (mSendSmsAction.checkForRegister()) {
            return;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            showProgress(true);
            registerPhone(mSendSmsAction.getSmsKey(), mSendSmsAction.getSmsCode(), username, password, mSendSmsAction.getCountryCode(), mSendSmsAction.getPhoneNum());
        }
    }

    private void registerPhone(String sms_key, String sms_code, String name, String password, String area, String phone) {
        getAppModel().getUserService().registerPhone(sms_key, sms_code, name, password, area, phone, new ModelCallback<UserInfo>() {
            @Override
            public void onBeforeRequest(String urlTag) {

            }

            @Override
            public void onSuccess(UserInfo data) {
                showProgress(false);
                Toast.makeText(getAppApplication(), "register success", Toast.LENGTH_SHORT).show();
                mActivity.startActivity(new Intent(mActivity, MainActivity.class));
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                showProgress(false);
                if ("3004".equals(errorEvent)) {
                    mCodesEdt.setError("验证码错误");
                    mCodesEdt.requestFocus();
                } else {
                    Toast.makeText(getAppApplication(), "register error", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
